import json
import datetime
from django.http import HttpResponse
from django.shortcuts import render
import os
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "green.settings")
django.setup()

# render请求
from green import models

city = ['北京', '天津', '河北', '山西', '内蒙古', '辽宁', '吉林', '黑龙江', '上海', '江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南',
        '广东', '广西']


def one(request):
    return render(request, "one/one.html")


# 汽车-城市数量统计
def showOne(request):
    year = request.GET.get('year')
    date = str(year)

    f = open('templates/one/bigJson_car.json', 'r', encoding='utf-8')
    bigJson = f.read()
    f.close()
    bigDict = json.loads(bigJson)
    data = bigDict[date]

    cars = {"data": data}
    response = HttpResponse(json.dumps(cars), content_type='application/json; charset=utf-8')
    return response


def initBigJsonForOne():
    bigJson = {}
    yearList = [['number_2016private', 'number_2016cargo', 'number_2016manned'],
                ['number_2017private', 'number_2017cargo', 'number_2017manned'], ['number_2018private',
                                                                                  'number_2018cargo',
                                                                                  'number_2018manned']]
    for oneyear in yearList:

        tempList = []
        queryCity = models.Cars.objects.values('provence', oneyear[0], oneyear[1], oneyear[2])
        print(queryCity);
        for item in queryCity:
            nums = 0
            for i in range(3):
                if item[oneyear[i]] is None:
                    continue
                else:
                    nums += item[oneyear[i]]
            tempList.append(
                {'city': str(item['provence']), 'num': nums})

        tempList.sort(key=lambda stu: stu["num"], reverse=True)
        print(tempList)
        # print(oneyear[0][7:11])
        bigJson[oneyear[0][7:11]] = tempList

    # 将bigJson保存为文件

    s = json.dumps(bigJson)
    f = open('../../templates/one/bigJson_car.json', 'w', encoding='UTF-8')
    f.write(s)
    f.close()
    print("构造bigJson.json成功！")
    return HttpResponse("构造成功！")


if __name__ == '__main__':
    initBigJsonForOne()
